package qif.reader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class QifReader {

	private List<QifTnansaction> list = new ArrayList<QifTnansaction>();
	private QifTnansaction current_tra = null;
	private int type = 0;

	private QifTnansaction currentTransaction() {
		if (current_tra == null) {
			current_tra = new QifTnansaction();
		}
		return current_tra;
	}

	private void newTransaction() {
		currentTransaction().setType(type);
		list.add(current_tra);
		current_tra = new QifTnansaction();
	}

	public List<QifTnansaction> getTransactionList() {
		return list;
	}

	private void switchMode(String str) {
		switch (str) {
		case "Account":
			type = QifTnansaction.ACCOUNT;
			break;

		case "Type:Cash":
			type = QifTnansaction.CASH;
			break;

		default:
			break;
		}
	}

	public void read(String file) throws Exception {
		File f = new File(file);
		try (BufferedReader qifin = new BufferedReader(new FileReader(f))) {
			String line;
			while ((line = qifin.readLine()) != null) {
				// start processing

				if (line.startsWith("!")) {
					String str = line.substring(1);
					switchMode(str);
				}

				if (line.startsWith("^")) {
					newTransaction();
				}

				if (line.startsWith("$")) {
					String str = line.substring(1);
					float val = Float.parseFloat(str);
					currentTransaction().setAmount(val);
				}

				if (line.startsWith("D")) {
					String str = line.substring(1);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy/M/dd");
					Date date = sdf.parse(str);
					currentTransaction().setTimestamp(date.getTime());
				}

				if (line.startsWith("M")) {
					String memo = line.substring(1);
					currentTransaction().setMemo(memo);
				}
			}
		}
	}
}
